package com.truthbean.jeetb.utils.web.invoker;

import com.truthbean.jeetb.utils.web.Utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class PortScanInvoker extends DefaultInvoker {
        public void invoke(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
            try {
                PrintWriter out = response.getWriter();
                ins.get("vPortScan").invoke(request, response, session);
                String ip = request.getParameter("ip");
                String ports = request.getParameter("ports");
                String timeout = request.getParameter("timeout");
                int iTimeout = 0;
                if (Utils.isEmpty(ip) || Utils.isEmpty(ports))
                    return;
                if (!Utils.isInteger(timeout)) {
                    timeout = "2";
                }
                iTimeout = Integer.parseInt(timeout);
                Map<String, String> rs = new LinkedHashMap<String, String>();
                String[] portArr = ports.split(",");
                for (String port : portArr) {
                    try {
                        Socket s = new Socket();
                        s.connect(new InetSocketAddress(ip, Integer.parseInt(port)), iTimeout);
                        s.close();
                        rs.put(port, "Open");
                    } catch (Exception e) {
                        rs.put(port, "Close");
                    }
                }
                out.println("<div style='margin:10px'>");
                Set<Map.Entry<String, String>> entrySet = rs.entrySet();
                for (Map.Entry<String, String> e : entrySet) {
                    String port = e.getKey();
                    String value = e.getValue();
                    out.println(ip + " : " + port + " ................................. <font color=" + (value.equals("Open") ? "green" : "red") + "><b>" + value + "</b></font><br>");
                }
                out.println("</div>");
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }
        }
    }